package com.petcare;

import java.util.ArrayList;
import com.bd.PetsModule;
import com.bd.AlarmsModule;
import com.bd.Utilities;

import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.view.View.OnClickListener;


public class setalarm extends Activity {
	
	TimePicker myTimePicker;
	Button buttonstartSetDialog;
	Calendar calendario;
	
	TimePickerDialog timePickerDialog;
	
	final static int RQS_1 = 1;
	AlarmsModule myAlarm = null;
    
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setalarm);
        try{
            Bundle bundle = this.getIntent().getExtras();
    	    myAlarm = Utilities.datasource.getAlarm(bundle.getInt("pk")+"");
    	    System.out.println(myAlarm);
    	    }
            catch(Exception e){
            	System.out.println("Exception: " +e);
           }
        final List<PetsModule> list = Utilities.datasource.getAllPets();
	    List<String> SpinnerArray =  new ArrayList<String>();
	    
	    for(int i = 0; i < list.size(); i++){
	    	
	    	final PetsModule pet = list.get(i);
	    	String nombre = pet.getName();
	    	SpinnerArray.add(nombre);
	    }
	    
	    	
	    
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SpinnerArray);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    final Spinner Items = (Spinner) findViewById(R.id.spinner2);
	    Items.setAdapter(adapter);
	    Items.setSelection(Integer.parseInt(myAlarm.getPetid())-1);
	  
	    
	    //Poner los valores en los campos
	    EditText actividad = (EditText)findViewById(R.id.editText1);
	    actividad.setText(myAlarm.getActivity());
	    CheckBox mo = (CheckBox)findViewById(R.id.checkBox1);
	    CheckBox tu = (CheckBox)findViewById(R.id.checkBox2);
		CheckBox we = (CheckBox)findViewById(R.id.checkBox3);
		CheckBox th = (CheckBox)findViewById(R.id.checkBox4);
		CheckBox fr = (CheckBox)findViewById(R.id.checkBox5);
		CheckBox sa = (CheckBox)findViewById(R.id.checkBox6);
		CheckBox su = (CheckBox)findViewById(R.id.checkBox7);
	    if(myAlarm.getDays().contains("Monday"))
	    	mo.setChecked(true);
	    if(myAlarm.getDays().contains("Tuesday"))
	    	tu.setChecked(true);
	    if(myAlarm.getDays().contains("Wednesday"))
	    	we.setChecked(true);
	    if(myAlarm.getDays().contains("Thursday"))
	    	th.setChecked(true);
	    if(myAlarm.getDays().contains("Friday"))
	    	fr.setChecked(true);
	    if(myAlarm.getDays().contains("Saturday"))
	    	sa.setChecked(true);
	    if(myAlarm.getDays().contains("Sunday"))
	    	su.setChecked(true);
	    if(myAlarm.getAmpm().equals("AM"))
	    	setTime(myAlarm.getHour(), myAlarm.getMinute(), 0);
	    else
	    	setTime(myAlarm.getHour(), myAlarm.getMinute(), 1);
	    
	    buttonstartSetDialog = (Button)findViewById(R.id.button1);
        buttonstartSetDialog.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				
				openTimePickerDialog(false);
				
			}});
      //Guardar
        Button bsave = (Button) findViewById(R.id.button2);
        bsave.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EditText actividad = (EditText)findViewById(R.id.editText1);
				String petID = String.valueOf(list.get(Items.getSelectedItemPosition()).getPk());
				System.out.println("PET ID: " + petID);
				String activity = actividad.getText().toString();
				
				String dias = "";
				CheckBox mo = (CheckBox)findViewById(R.id.checkBox1);
				CheckBox tu = (CheckBox)findViewById(R.id.checkBox2);
				CheckBox we = (CheckBox)findViewById(R.id.checkBox3);
				CheckBox th = (CheckBox)findViewById(R.id.checkBox4);
				CheckBox fr = (CheckBox)findViewById(R.id.checkBox5);
				CheckBox sa = (CheckBox)findViewById(R.id.checkBox6);
				CheckBox su = (CheckBox)findViewById(R.id.checkBox7);
				if(mo.isChecked())
					dias += "Monday,";
				if(tu.isChecked())
					dias += "Tuesday,";;
				if(we.isChecked())
					dias += "Wednesday,";
				if(th.isChecked())
					dias += "Thursday,";
				if(fr.isChecked())
					dias += "Friday,";
				if(sa.isChecked())
					dias += "Saturday,";
				if(su.isChecked())
					dias += "Sunday,";
				
				int hora = calendario.get(Calendar.HOUR);
				System.out.println("HORA: " + hora);
				int minute = calendario.get(Calendar.MINUTE);
				System.out.println("MINUTE: " + minute);
				String ampm = "PM";
				int valor = calendario.get(Calendar.AM_PM);
				if(valor == 0)
					ampm = "AM";
				System.out.println("AM PM: " +ampm);
				myAlarm.setActivity(activity);
				myAlarm.setPetid(petID);
				myAlarm.setAmpm(ampm);
				myAlarm.setDays(dias);
				myAlarm.setHour(hora);
				myAlarm.setMinute(minute);
				Utilities.datasource.updateAlarm(myAlarm);
				setAlarm(calendario);
			}
		});

    }

		
	private void openTimePickerDialog(boolean is24r){
		Calendar calendar = Calendar.getInstance();
		
		timePickerDialog = new TimePickerDialog(
				setalarm.this, 
				onTimeSetListener, 
				myAlarm.getHour(), 
				myAlarm.getMinute(), 
				is24r);
		timePickerDialog.setTitle("Set Alarm Time");  
        
		timePickerDialog.show();

	}
    
    OnTimeSetListener onTimeSetListener
    = new OnTimeSetListener(){

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			Calendar calNow = Calendar.getInstance();
			Calendar calSet = (Calendar) calNow.clone();

			calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
			calSet.set(Calendar.MINUTE, minute);
			calSet.set(Calendar.SECOND, 0);
			calSet.set(Calendar.MILLISECOND, 0);
			
			
			if(calSet.compareTo(calNow) <= 0){
				//Today Set time passed, count to tomorrow
				calSet.add(Calendar.DATE, 1);
			}
		
			calendario = calSet;
		}};

	private void setAlarm(Calendar targetCal){

		final EditText txtTexto = (EditText)findViewById(R.id.editText1);
		String texto = txtTexto.getText().toString();
		
		Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
		intent.putExtra("msg", texto);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
		AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
		
		Toast.makeText(getBaseContext(), "Alarm created!", Toast.LENGTH_SHORT).show();
		
	}
	
	public void setTime(int hourOfDay, int minute, int ampm) {

		Calendar calNow = Calendar.getInstance();
		Calendar calSet = (Calendar) calNow.clone();

		calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
		calSet.set(Calendar.MINUTE, minute);
		calSet.set(Calendar.SECOND, 0);
		calSet.set(Calendar.MILLISECOND, 0);
		calSet.set(Calendar.AM_PM, ampm);
		
		if(calSet.compareTo(calNow) <= 0){
			//Today Set time passed, count to tomorrow
			calSet.add(Calendar.DATE, 1);
		}
	
		calendario = calSet;
	}
}
